/*
 * app_host.cpp  
 *
 #define NID int
 int getHostInfo(NID nid, char *result)
 成功时返回1，否则返回0

 内部实现的内容：生成请求用的XML，发送到消息队列，从FIFO里得到结果，把结果写到result里
 以静态lib文件的形式

 外部使用的方法：
 char buf[2048];
 getHostInfo(1024, buf);
 */

#include "app_host.h"
#include "../tinyxml/cpuxml.h"
#include "../msgqueue/MsgQue.h"
#include "../utilize/timeout.h"

#include <string>
#include <unistd.h>
#include	<fcntl.h>
#include <iostream>
using namespace std;

static const int CBUFFSIZE = 2048;

MsgQue msgQue("/", 0);
unsigned int bonus = 0;

int getHostInfo(unsigned char *nid, char *result)
{
	srand(time(0));
	CPU_XML xml;
	xml.setTitle("ContextRequest");
	xml.setType("resourceInfo");
	xml.setOper("query");
	xml.setNID(nid);

	int done = -1;
	int tmp, fdread, nread;
	char fifoName[32];
	char msg[MBUFSIZ];

	while (done) //总会找到一个可用的整数的
	{
		tmp = rand() + pthread_self() + (bonus++);
		sprintf(fifoName, "/tmp/context%d.fifo", tmp);
		done = mkfifo(fifoName, O_RDWR);
	}
	xml.setReqID(tmp);

	xml.formXML(msg);
	msgQue.send(1, msg);
//	cout << "id: " << tmp << endl;;


	if ((fdread = open(fifoName, O_RDONLY | O_NONBLOCK, 0)) < 0)
	{
		printf("open error for reading\n");
		return 0;
	}

	tmp = readReady(fdread, 0, 500000);
	if (tmp)
	{
		nread = read(fdread, result, CBUFFSIZE);
		//printf("Received %ld bytes: %s\n", (long) nread, result);
	}

	close(fdread);
	unlink(fifoName);

	return 1;
}

int main()
{
	char buf[CBUFFSIZE];
	bzero(buf, CBUFFSIZE);
//	for (int i = 0; i < 5; i++)
	getHostInfo((unsigned char *)"1212", buf);
	cout << buf << endl;
	return 0;
}
